#include "playpagewidget.h"
#include "ui_playpagewidget.h"
#include "songmanager.h"
#include <QPropertyAnimation>
#include <QDebug>
PlayPageWidget::PlayPageWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PlayPageWidget)
{
    ui->setupUi(this);
    ui->songImage->setAlignment(Qt::AlignCenter);
}

PlayPageWidget::~PlayPageWidget()
{
    delete ui;
}

void PlayPageWidget::movePage()
{
    if (_isMoving){
        qDebug() << "在动了在动了";
        return;
    }

    QRect dst({10,                       10}, QSize(parentWidget()->width()-20, parentWidget()->height()-20-120));
    QRect mid({10,parentWidget()->height()/2},QSize(parentWidget()->width()-20, parentWidget()->height()-20-120));
    QRect src({10, parentWidget()->height()}, QSize(parentWidget()->width()-20, parentWidget()->height()-20-120));
    if(_isUp) std::swap(dst, src);

    qDebug() << "MovePage起始于: " << src << "， 终止于: " << dst;
    QPropertyAnimation* animation = new QPropertyAnimation(this, "geometry");
    animation->setStartValue(src);
    animation->setKeyValueAt(0.7, mid);
    animation->setEndValue(dst);
    animation->setDuration(250);

    _isUp = !_isUp;
    _isMoving = true;
    show();
    raise();
    animation->start();
    connect(animation, &QPropertyAnimation::finished, this, [=]{
        animation->deleteLater();
        this->_isMoving = false;
        if(_isUp == false) {
            hide();
            emit changeColor("rgb(250, 250, 250)");
        } else {
            if(color.isValid()){
                QColor color3 = color;
                double x = 0.6;
                color3.setRed(color.red() * x);
                color3.setGreen(color.green() * x);
                color3.setBlue(color.blue() * x);
                emit changeColor(QString("rgb(%1, %2, %3)").arg(color3.red()).arg(color3.green()).arg(color3.blue()));
            }
        }
    });
}
#include <QtMath>

static double luminance(const QColor &color) {
    auto channel = [](double c) {
        c /= 255.0;
        return (c <= 0.03928) ? (c / 12.92) : qPow((c + 0.055) / 1.055, 2.4);
    };
    return 0.2126 * channel(color.red()) +
           0.7152 * channel(color.green()) +
           0.0722 * channel(color.blue());
}

static double contrastRatio(const QColor &c1, const QColor &c2) {
    double l1 = luminance(c1);
    double l2 = luminance(c2);
    if (l1 < l2) std::swap(l1, l2);
    return (l1 + 0.05) / (l2 + 0.05);
}


QColor getBackGroundColor(const QPixmap &pixmap)
{
    // 默认为灰色
    if (pixmap.isNull()) return QColor("#2c2c2c");
    QImage image(pixmap.toImage());
    // 压到一像素获取平均颜色,不过应该有更专业的做法,但我不会
    QImage imageScaled = image.scaled(1, 1, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    QColor avgColor = imageScaled.pixelColor(0, 0);

    // 文字颜色：白色 和 rgb(115,117,128)
    QColor text1(255, 255, 255);
    QColor text2(115, 117, 128);

    // 检查与文字的对比度
    double contrast1 = contrastRatio(avgColor, text1);
    double contrast2 = contrastRatio(avgColor, text2);

    // 如果对比度太低，则加深背景色直到至少 4.5:1(最多试5次,不然都会变成黑色)
    int attempt = 0;
    while ((contrast1 < 4.5 || contrast2 < 4.5) && attempt < 5) {
        avgColor = avgColor.darker(120); // 每次加深 20%
        contrast1 = contrastRatio(avgColor, text1);
        contrast2 = contrastRatio(avgColor, text2);
        attempt++;
    }

    return avgColor;
}

#include <QPainter>
void PlayPageWidget::updateCurrentSongImage(const QPixmap &image)
{
    QSize size = ui->songImage->size();
    QPixmap scaledSongImage = image.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    _currentSongImage = QPixmap(size);
    _currentSongImage.fill(Qt::transparent);

    QPainter painter(&_currentSongImage);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QBrush(scaledSongImage));
    painter.drawRoundedRect(scaledSongImage.rect(), size.width(), size.height());

    color = getBackGroundColor(image);
    QColor color2 = color; // 避免 alpha 为 0（透明）

    double x = 0.7;
    color2.setRed(color.red() * x);
    color2.setGreen(color.green() * x);
    color2.setBlue(color.blue() * x);

    // 渐变,从上到下的颜色变深
    QString backgroundColor = QString(
        "border-top-left-radius: 12px; "
        "border-top-right-radius: 12px; "
        "background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "stop:0 rgb(%1, %2, %3), "
        "stop:1 rgb(%4, %5, %6));" // 这样设置可以尽量避免格式错误
    ).arg(color.red()).arg(color.green()).arg(color.blue())
     .arg(color2.red()).arg(color2.green()).arg(color2.blue());
    QString style = "#playPage {" + backgroundColor + "}";
    ui->playPage->setStyleSheet(style);

    if(_isUp){
        QColor color3 = color;
        double x = 0.6;
        color3.setRed(color.red() * x);
        color3.setGreen(color.green() * x);
        color3.setBlue(color.blue() * x);
        emit changeColor(QString("rgb(%1, %2, %3)").arg(color3.red()).arg(color3.green()).arg(color3.blue()));
    }
}

void PlayPageWidget::setAngleOfImage(qreal angle)
{
    QTransform transform;
    QPointF center(_currentSongImage.width()/2.0, _currentSongImage.height()/2.0);
    transform.translate(center.x(), center.y());
    transform.rotate(angle);
    transform.translate(-center.x(), -center.y());
    QPixmap rotatedPixmap = _currentSongImage.transformed(transform, Qt::SmoothTransformation);
    ui->songImage->setPixmap(rotatedPixmap);
}

void PlayPageWidget::updateCurUrl(const QUrl &url)
{
    _currentUrl = url;
    ui->lrc->updateCurUrl(url);
    const SongItem& item = SongManager::instance()->getSongItem(url);
    ui->songTitle->setText(item.name);
    ui->songArtist->setText("歌手: " + item.artist);
    ui->songAlbum->setText("专辑: " + item.album);
}

void PlayPageWidget::setCurTime(qint64 time)
{
    ui->lrc->updateCurDuration(time);
}

//void PlayPageWidget::on_pushButton_playPause_clicked()
//{
//    qDebug() << "播放界面的播放按钮被点击";
//}

void PlayPageWidget::on_pushButton_clicked()
{
    movePage();
}
